<template>
  <div>
    <div style="margin-bottom: 16px;">
      <a-button type="primary" @click="showTemplateModal">
        <a-icon type="plus" /> 新建模板
      </a-button>
      <a-divider type="vertical" />
      <a-select
        v-model="selectedSemester"
        style="width: 200px; margin-right: 16px;"
        placeholder="请选择学年学期"
      >
        <a-select-option value="2022-2024-1">2022-2023学年第一学期</a-select-option>
        <a-select-option value="2022-2024-2">2022-2023学年第二学期</a-select-option>
        <a-select-option value="2024-2024-1">2024-2024学年第一学期</a-select-option>
      </a-select>
      
      <a-select
        v-model="selectedType"
        style="width: 150px;"
        placeholder="请选择模板类型"
      >
        <a-select-option value="all">全部类型</a-select-option>
        <a-select-option value="student">学生评价</a-select-option>
        <a-select-option value="supervisor">督导评价</a-select-option>
        <a-select-option value="leader">领导评价</a-select-option>
      </a-select>
    </div>

    <a-table
      :columns="columns"
      :dataSource="filteredTemplates"
      rowKey="id"
      :pagination="false"
    >
      <template slot="type" slot-scope="text">
        <a-tag :color="getTypeColor(text)">{{text}}</a-tag>
      </template>
      <template slot="status" slot-scope="text">
        <a-badge :status="text === '启用' ? 'success' : 'default'" :text="text" />
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button type="link" size="small" @click="editTemplate(record)">编辑</a-button>
        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="toggleStatus(record)">
          {{record.status === '启用' ? '停用' : '启用'}}
        </a-button>
        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="copyTemplate(record)">复制</a-button>
        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="deleteTemplate(record)">删除</a-button>
      </template>
    </a-table>

    <a-modal
      :title="templateModalTitle"
      :visible="templateModalVisible"
      @ok="handleTemplateOk"
      @cancel="handleTemplateCancel"
      :width="1000"
    >
      <a-form :form="templateForm" layout="vertical">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="模板名称">
              <a-input
                v-decorator="['name', { rules: [{ required: true, message: '请输入模板名称' }] }]"
                placeholder="请输入模板名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="模板类型">
              <a-select
                v-decorator="['type', { rules: [{ required: true, message: '请选择模板类型' }] }]"
                placeholder="请选择模板类型"
              >
                <a-select-option value="student">学生评价</a-select-option>
                <a-select-option value="supervisor">督导评价</a-select-option>
                <a-select-option value="leader">领导评价</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="适用学年学期">
          <a-select
            v-decorator="['semester', { rules: [{ required: true, message: '请选择学年学期' }] }]"
            placeholder="请选择学年学期"
          >
            <a-select-option value="2022-2024-1">2022-2023学年第一学期</a-select-option>
            <a-select-option value="2022-2024-2">2022-2023学年第二学期</a-select-option>
            <a-select-option value="2024-2024-1">2024-2024学年第一学期</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="模板描述">
          <a-textarea
            v-decorator="['description']"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </a-form-item>

        <a-form-item label="指标配置">
          <a-transfer
            :data-source="indicatorData"
            :target-keys="targetKeys"
            :render="item => item.title"
            @change="handleTransferChange"
            :titles="['可选指标', '已选指标']"
            :list-style="{ width: '45%', height: '300px' }"
          />
        </a-form-item>

        <a-form-item label="状态">
          <a-switch
            v-decorator="['status', { valuePropName: 'checked', initialValue: true }]"
            checked-children="启用"
            un-checked-children="停用"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      columns: [
        {
          title: '模板名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '模板类型',
          dataIndex: 'type',
          key: 'type',
          scopedSlots: { customRender: 'type' },
          width: 120
        },
        {
          title: '学年学期',
          dataIndex: 'semester',
          key: "semester",
          width: 180
        },
        {
          title: '指标数量',
          dataIndex: 'indicatorCount',
          key: 'indicatorCount',
          width: 100
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' },
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 220
        }
      ],
      templates: [
        {
          id: '1',
          name: '学生评价标准模板',
          type: '学生评价',
          semester: '2022-2024-2',
          description: '学生评价教师教学质量的标准模板',
          indicators: ['1', '2', '3', '4'],
          indicatorCount: 4,
          status: '启用'
        },
        {
          id: '2',
          name: '督导评价详细模板',
          type: '督导评价',
          semester: '2022-2024-2',
          description: '督导评价教师教学质量的详细模板',
          indicators: ['1', '2', '3', '4', '5', '6'],
          indicatorCount: 6,
          status: '启用'
        },
        {
          id: '3',
          name: '领导评价简化模板',
          type: '领导评价',
          semester: '2024-2024-1',
          description: '领导评价教师教学质量的简化模板',
          indicators: ['1', '4'],
          indicatorCount: 2,
          status: '停用'
        }
      ],
      indicatorData: [
        {
          key: '1',
          title: '教学态度认真负责',
          description: '教师备课充分，授课认真，对学生负责'
        },
        {
          key: '2',
          title: '教学内容充实',
          description: '教学内容丰富，信息量大，符合教学大纲要求'
        },
        {
          key: '3',
          title: '教学方法得当',
          description: '教学方法灵活多样，能激发学生学习兴趣'
        },
        {
          key: '4',
          title: '教学效果良好',
          description: '学生能够掌握课程主要内容，达到教学目标'
        },
        {
          key: '5',
          title: '课堂互动良好',
          description: '师生互动积极，课堂气氛活跃'
        },
        {
          key: '6',
          title: '作业批改认真',
          description: '作业批改及时，反馈详细'
        }
      ],
      selectedSemester: 'all',
      selectedType: 'all',
      templateModalVisible: false,
      templateModalTitle: '新建模板',
      currentTemplate: null,
      targetKeys: []
    }
  },
  computed: {
    filteredTemplates() {
      let result = [...this.templates]
      if (this.selectedSemester !== 'all') {
        result = result.filter(item => item.semester === this.selectedSemester)
      }
      if (this.selectedType !== 'all') {
        result = result.filter(item => item.type === this.selectedType)
      }
      return result
    }
  },
  beforeCreate() {
    this.templateForm = this.$form.createForm(this, { name: 'template_form' })
  },
  methods: {
    getTypeColor(type) {
      const colors = {
        '学生评价': 'green',
        '督导评价': 'blue',
        '领导评价': 'purple'
      }
      return colors[type] || 'default'
    },
    showTemplateModal() {
      this.currentTemplate = null
      this.templateModalTitle = '新建模板'
      this.templateModalVisible = true
      this.targetKeys = []
      this.$nextTick(() => {
        this.templateForm.resetFields()
      })
    },
    editTemplate(record) {
      this.currentTemplate = record
      this.templateModalTitle = '编辑模板'
      this.templateModalVisible = true
      this.targetKeys = [...record.indicators]
      this.$nextTick(() => {
        this.templateForm.setFieldsValue({
          name: record.name,
          type: record.type.replace('评价', ''),
          semester: record.semester,
          description: record.description,
          status: record.status === '启用'
        })
      })
    },
    toggleStatus(record) {
      record.status = record.status === '启用' ? '停用' : '启用'
      this.$message.success(`已${record.status}模板`)
    },
    copyTemplate(record) {
      const newTemplate = {
        ...record,
        id: `template_${Date.now()}`,
        name: `${record.name}(副本)`,
        status: '停用'
      }
      this.templates.push(newTemplate)
      this.$message.success('复制成功')
    },
    deleteTemplate(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除模板"${record.name}"吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.templates = this.templates.filter(item => item.id !== record.id)
          this.$message.success('删除成功')
        }
      })
    },
    handleTemplateOk() {
      this.templateForm.validateFields((err, values) => {
        if (!err) {
          const template = {
            name: values.name,
            type: `${values.type}评价`,
            semester: values.semester,
            description: values.description,
            indicators: [...this.targetKeys],
            indicatorCount: this.targetKeys.length,
            status: values.status ? '启用' : '停用'
          }
          
          if (this.currentTemplate) {
            // 更新
            Object.assign(this.currentTemplate, template)
            this.$message.success('更新成功')
          } else {
            // 新增
            const newTemplate = {
              id: `template_${Date.now()}`,
              ...template
            }
            this.templates.push(newTemplate)
            this.$message.success('添加成功')
          }
          this.templateModalVisible = false
        }
      })
    },
    handleTemplateCancel() {
      this.templateModalVisible = false
    },
    handleTransferChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    }
  }
}
</script>